/*
 WiFi Web Server LED Blink

 A simple web server that lets you blink an LED via the web.
 This sketch will print the IP address of your WiFi Shield (once connected)
 to the Serial monitor. From there, you can open that address in a web browser
 to turn on and off the LED on pin 5.

 If the IP address of your shield is yourAddress:
 http://yourAddress/H turns the LED on
 http://yourAddress/L turns it off

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * WiFi shield attached
 * LED attached to pin 5

 created for arduino 25 Nov 2012
 by Tom Igoe

ported for sparkfun esp32 
31.01.2017 by Jan Hendrik Berlin
 
 */

#define ADC_EN              14  //ADC_EN is the ADC detection enable port
#define ADC_PIN             34
#define BUTTON_1            35
#define BUTTON_2            0
#include <TFT_eSPI.h> //Graphics and font lib for ST7735 driver chip
#include <SPI.h>
#include <WiFi.h>
#include <Wire.h>
#include "Button2.h"
#include "esp_adc_cal.h"

int vref = 1100;
const char* ssid     = "ChinaNet-yu";
const char* password = "ydd200706";
TFT_eSPI tft = TFT_eSPI();
Button2 btn1(BUTTON_1);
Button2 btn2(BUTTON_2);

WiFiServer server(80);

int ScreenBackgroundColor=TFT_BLACK;

void cls()
{
  tft.fillScreen(ScreenBackgroundColor); 
  tft.setCursor(0,0); 
}

String getVoltage()
{
  String voltage="";
    static uint64_t timeStamp = 0;
    if (millis() - timeStamp > 1000) {
        timeStamp = millis();
        uint16_t v = analogRead(ADC_PIN);
        float battery_voltage = ((float)v / 4095.0) * 2.0 * 3.3 * (vref / 1000.0);
        voltage = " " + String(battery_voltage) + "V";
    }
    return voltage;
}
size_t print(const String& x)
{
  Serial.print(x); 
  return tft.print(x); 
  }
  
size_t println(const String& x)
{
  Serial.println(x); 
  return tft.println(x); 
  }

void button_init()
{
    btn1.setLongClickHandler([](Button2 & b) {
//    btnCick = false;
        int r = digitalRead(TFT_BL);
//        tft.fillScreen(TFT_BLACK);
//        tft.setTextColor(TFT_GREEN, TFT_BLACK);
//        tft.setTextDatum(MC_DATUM);
//        tft.drawString("Press again to wake up",  tft.width() / 2, tft.height() / 2 );
//        espDelay(6000);
        digitalWrite(TFT_BL, !r);

        tft.writecommand(TFT_DISPOFF);
        tft.writecommand(TFT_SLPIN);
        //After using light sleep, you need to disable timer wake, because here use external IO port to wake up
        esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER);
        // esp_sleep_enable_ext1_wakeup(GPIO_SEL_35, ESP_EXT1_WAKEUP_ALL_LOW);
        esp_sleep_enable_ext0_wakeup(GPIO_NUM_35, 0);
        delay(200);
        esp_deep_sleep_start();
    });
    btn1.setPressedHandler([](Button2 & b) {
        Serial.println("Detect Voltage..");
        //btnClick = true;
    });

    btn2.setPressedHandler([](Button2 & b) {
        //btnClick = false;
        println("btn press wifi scan");
        cls();
        println(getVoltage());
    });
}

void button_loop()
{
    btn1.loop();
    btn2.loop();
}


void setup()
{
    Serial.begin(115200);
    //pinMode(5, OUTPUT);      // set the LED pin mode
    delay(10);
    
    tft.init();
    tft.setRotation(1);
    tft.fillScreen(TFT_BLACK);
    tft.setTextColor(TFT_YELLOW,TFT_BLACK);
    tft.setTextSize(2);
    tft.setTextWrap(240,135);

    button_init();

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    
    print("WiFi:");
    println(ssid);
    print(__DATE__ );
    println(getVoltage());
    
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        print(".");
        button_loop();    
    }

    cls();
    print("WiFi:");
    println(ssid);
    print("IP:");
    tft.println(WiFi.localIP());
    Serial.println(WiFi.localIP());
    println(getVoltage());
    server.begin();
    tft.setTextColor(TFT_GREEN,TFT_BLACK);
    tft.println("Web Server ready.");
  
}

int value = 0;

void loop(){
 tft.setTextColor(TFT_WHITE,TFT_BLACK);
 WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("New Client.");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click <a href=\"/H\">here</a> to turn the LED on pin 5 on.<br>");
            client.print("Click <a href=\"/L\">here</a> to turn the LED on pin 5 off.<br>");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {    // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
        
        
        if(currentLine.endsWith("HTTP/1.1")){
          currentLine.replace("GET /","");
          currentLine.replace("HTTP/1.1","");
          currentLine.replace("%20"," ");

          cls();
          tft.setTextColor(TFT_PURPLE,TFT_BLACK);
          print("Mini web server");
          println(getVoltage());
          tft.setTextColor(TFT_GREEN,TFT_BLACK);
          tft.println("-------------------");
          
          tft.setTextColor(TFT_WHITE,TFT_BLACK);
          tft.println(currentLine);
        }
        
//        // Check to see if the client request was "GET /H" or "GET /L":
//        if (currentLine.endsWith("GET /H")) {
//          //digitalWrite(5, HIGH);               // GET /H turns the LED on
//        }
//        if (currentLine.endsWith("GET /L")) {
//          //digitalWrite(5, LOW);                // GET /L turns the LED off
//        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("Client Disconnected.");
  }
  button_loop();
}
